package cn.tedu.order.tx;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.mapper.TxMapper;
import cn.tedu.order.service.OrderService;
import cn.tedu.order.util.JsonUtil;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
public class TxOrderService implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private TxMapper txMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Override
    public void create(Order order) {
        //不直接创建订单，而是发送事务消息
        //发消息时，会触发监听器执行本地事务

        //生成xid
        String xid = UUID.randomUUID().toString().replace("-","");

        TxAccountMessage msg = new TxAccountMessage();
        msg.setUserId(order.getUserId());
        msg.setMoney(order.getMoney());
        msg.setXid(xid);

        String json = JsonUtil.to(msg);
        // json 封装成 spring 的一个通用消息对象
        Message<String> message = MessageBuilder.withPayload(json).build();

        //rocketMQTemplate.sendMessageInTransaction("order-topic",消息，执行本地事务需要的业务数据)
        rocketMQTemplate.sendMessageInTransaction("order-topic",message,order);

    }

    //完成订单的添加
    @Transactional
    public void doCreate(Order order){
        Long orderId = Long.valueOf(easyIdClient.getNextId("order_business"));
        order.setId(orderId);
        orderMapper.create(order);

    }
}
